<template>
    <div>
      <van-popup v-model="showSelect" position="bottom" :close-on-click-overlay="false" round
        @click-overlay="onCloseInvoiceSelect" class="invoice-select">
        <div class="invoice-select-inner" @click="chooseHead">
          <div class="close-input">
            <i class="iconfont icon-icon_close ET4" @click="onCloseInvoiceSelect"></i>
          </div>
          <div class="invoice-select-title ET4">{{t('invoice_title')}}</div>
          <div class="invoice-select-content">
            <div v-show="isWeChatEnv" class="use-wechat MB4 theme-customize-font" @click="onUseWechat">
              {{t('invoice_weChat_title')}}
              <span class="iconfont icon-zhixiang theme-customize-font"></span>
            </div>
            <div class="invoice-select-tip MB2">
              <div class="type-title">{{t('invoice_type')}}</div>
              <div class="notice ET0 EC3" @click="showTip = true">
                {{t('invoice_view_invoice_notes')}}
                <i class="iconfont icon-tishi ET0"></i>
              </div>
            </div>
            <div class="invoice-select-remind MB3 ET0 EC3">
              {{t('invoice_select_remind')}}
            </div>
            <div class="invoice-select-button MB4 ET0">
              <button v-for="item in invoiceForm" :key="item.id" :class="item.class" @click="choiceType(item.id)">
                {{ item.title }}
              </button>
            </div>
            <div class="input-top MB2">{{t('invoice_the_title')}}</div>
            <div class="invoice-select-input MB3 invoice-head">
              <input v-model="invoiceMessage.invoiceHead" :placeholder="`${t('invoice_enter_the')}${invoiceForm[invoiceMessage.invoiceType - 1].title}${t('invoice_name')}`
                " @blur.prevent="onBlur" @focus.prevent="onFocus" />
              <div class="invoice-head-list" v-show="companyInvoiceInfo.length">
                <div class="head-item" v-for="(item, index) in companyInvoiceInfo" :key="index"
                  @click.stop="chooseHead(item)">{{ item.name }}</div>
              </div>
            </div>
            <div class="input-top MB2" v-show="invoiceForm[invoiceMessage.invoiceType - 1].showTaxNumber">
              {{t('invoice_enterprise_duty_paragraph')}}
            </div>
            <div class="invoice-select-input MB3" v-show="invoiceForm[invoiceMessage.invoiceType - 1].showTaxNumber">
              <input v-model="invoiceMessage.taxNumber" :placeholder='t("invoice_enter_enterprise")' @blur.prevent="onBlur"
                @focus.prevent="onFocus" />
            </div>
            <div v-show="invoiceForm[invoiceMessage.invoiceType - 1].showMoreInfo">
              <div class="invoice-select-moreInfo">
                <div>
                  <span class="input-top">{{t('invoice_more_options')}}</span>
                  <span class="ML2 ET0 EC3">{{t('invoice_options')}}</span>
                </div>
                <div class="show-info" @click="isShowInfo">
                  <span class="ET0 EC3">{{ showInfo ? t('invoice_close') : t('invoice_expand') }}</span>
                  <img v-if="showInfo" src="../../assets/arrow_up.png">
                  <img v-else src="../../assets/arrow_down.png" alt="">
                </div>
              </div>
              <div v-show="showInfo" class="invoice-select-info">
                <div class="MT2">
                  <span class="input-top">{{t('invoice_registered_address')}}</span>
                  <input v-model="invoiceMessage.invoiceTaxAddress" class="input-border ML5" type="text"
                    :placeholder='t("invoice_fill_registered_address")' @blur.prevent="onBlur" @focus.prevent="onFocus" />
                </div>
                <div class="MT2">
                  <span class="input-top">{{t('invoice_phone_number')}}</span>
                  <input v-model="invoiceMessage.invoiceTaxPhone" class="input-border ML5" type="text" :placeholder='t("invoice_fill_phone_number")'
                    @blur.prevent="onBlur" @focus.prevent="onFocus"
                    @input="invoiceMessage.invoiceTaxPhone = clearNoNum(invoiceMessage.invoiceTaxPhone)"
                    @change="invoiceMessage.invoiceTaxPhone = clearNoNum(invoiceMessage.invoiceTaxPhone)" />
                </div>
                <div class="MT2">
                  <span class="input-top">{{t('invoice_bank_account')}}</span>
                  <input v-model="invoiceMessage.invoiceTaxBank" class="input-border ML5" type="text"
                    :placeholder='t("invoice_fill_bank_account")' @blur.prevent="onBlur" @focus.prevent="onFocus" />
                </div>
                <div class="MT2">
                  <span class="input-top">{{t('invoice_account_number')}}</span>
                  <input v-model="invoiceMessage.invoiceTaxBankAccount" class="input-border ML5" type="text"
                    :placeholder='t("invoice_fill_account_number")' @blur.prevent="onBlur" @focus.prevent="onFocus" />
                </div>
              </div>
            </div>
            <div class="invoice-select-category" v-show="showClass">
              <div class="input-top MB2">{{t('invoice_content')}}</div>
              <div class="invoice-select-remind MB3 EC3 ET0">
                {{t('invoice_displays')}}{{ this.invoiceContent }}{{t('invoice_name')}}
              </div>
              <div class="invoice-select-button ET0 MB3">
                <button :class="item.class" @click="choiceClass(item.id)" v-for="item in invoiceClass" :key="item.id">
                  {{ item.title }}
                </button>
              </div>
            </div>
            <div class="input-top MB2">{{t('invoice_email')}}</div>
            <div class="invoice-select-input MB3">
              <input v-model="invoiceMessage.invoiceEmail" :placeholder='t("invoice_send_electronic")' @blur.prevent="onBlur"
                @focus.prevent="onFocus" />
            </div>
            <div class="input-top MB2">{{t('invoice_phone')}}</div>
            <div class="invoice-select-input MB3">
              <input v-model="invoiceMessage.invoicePhone" :placeholder='t("invoice_send_electronic")' @blur.prevent="onBlur"
                @focus.prevent="onFocus" />
            </div>
          </div>
          <div class="invoice-select-foot" v-fixIosBottom="{ paddingBottom: '0.5rem' }">
            <button @click="onSubmit" class="theme-customize-bg">{{t('invoice_complete')}}</button>
          </div>
        </div>
      </van-popup>
      <invoice-tip :showTip="showTip" @closeTip="showTip = false"></invoice-tip>
    </div>
  </template>
  
  <script>
  import { request } from "@xiaoe/js-tools/lib/request";
  import { isEmptyObject } from "../../utils";
  import { isWechat } from "../../utils/checkEnv";
  import invoiceTip from "./InvoiceTip";
  import locale from "../../../../mixins/locale";

  export default {
    name: 'InvoiceSelect',
    props: {
      //是否显示发票选择器
      showSelect: {
        type: Boolean,
        default: false,
      },
      shopConf: {
        type: Object,
        default: () => ({})
      },
      invoiceInfo: {
        type: Object,
        default: () => ({})
      }
    },
    mixins: [locale],
    components: {
      invoiceTip
    },
    data() {
      return {
        show: true, // 是否显示发票选择组件
        showTip: false, // 是否显示发票须知
        invoiceClassData: [], // 发票类别显示内容信息
        // 发票类型信息
        invoiceForm: [
          { id: 1, title: this.t("invoice_enterprise"), showTaxNumber: true, showMoreInfo: true, class: "active theme-customize-bg-light theme-customize-border" },
          { id: 2, title: this.t("invoice_personal"), showTaxNumber: false, class: "" },
        ], // 发票类型信息
        invoiceClass: [], // 发票类别信息
        showClass: true, // 是否显示发票类别
        eleFocus: "", // 正在获取焦点的元素
        invoiceContent: "",
        invoiceMessage: {
          invoiceHead: "", // 发票抬头
          taxNumber: "", // 企业税号
          invoiceType: 1, // 发票类型
          invoiceCategory: 1, // 发票类别
          invoiceEmail: "", // 发票邮箱,
          invoiceState: 0, // 状态
          invoicePhone: "", // 收票手机号
          invoiceTaxAddress: "",  // 注册地址
          invoiceTaxPhone: "",  // 注册电话
          invoiceTaxBank: "", // 开户隐含
          invoiceTaxBankAccount: "", // 银行账号
        }, // 发票信息
        showInfo: false, // 是否展示更多选填项
        companyInvoiceInfo: [], // 搜索的发票抬头信息
        isAllowSearch: true,
      };
    },
    mounted() {
      if (!isEmptyObject(this.shopConf)) {
        this.onEnsureInvoiceClass();
      }
      this.changeInvoiceMessage(this.invoiceInfo);
    },
    computed: {
      // 判断是否在微信环境中
      isWeChatEnv() {
        return false;
        // return isWechat;
      }
    },
    watch: {
      //监听shopConf'
      shopConf: {
        handler() {
          this.onEnsureInvoiceClass();
        },
        deep: true,
      },
      invoiceInfo: {
        handler(val) {
          this.changeInvoiceMessage(val);
        },
        deep: true,
      },
      "invoiceMessage.invoiceHead": {
        handler(newV, oldV) {
          // 值没变化不触发接口
          if (!newV || !this.isAllowSearch) {
            this.companyInvoiceInfo = [];
            this.isAllowSearch = true;
            return;
          }
          if (newV === oldV || this.invoiceMessage.invoiceType === 2) {
            return;
          }
          this.getCompanyInvoiceInfo();
        },
        deep: true
      }
    },
    methods: {
      // 选择抬头
      chooseHead(item) {
        if (item.name) {
          this.isAllowSearch = false;
          this.invoiceMessage.invoiceHead = item.name;
          this.invoiceMessage.taxNumber = item.taxno;
          this.invoiceMessage.invoiceTaxAddress = item.address;
          this.invoiceMessage.invoiceTaxPhone = item.telephone;
          this.invoiceMessage.invoiceTaxBank = item.buyerBankName;
          this.invoiceMessage.invoiceTaxBankAccount = item.buyerBankNo;
        }
        this.companyInvoiceInfo = [];
      },
      // 发票抬头模糊查询
      getCompanyInvoiceInfo() {
        const params = {
          key_word: this.invoiceMessage.invoiceHead || ''
        }
        request({
          url: "/xe.transaction.invoice.get_company_invoice_info/1.0.0",
          params
        }).then(res => {
          if (res.code === 0) {
            this.companyInvoiceInfo = res.data || [];
          } else {
            this.companyInvoiceInfo = [];
          }
        }).catch(err => {
          this.$skynet.report({
            details: {
              keyword: "onfirmOrderPage_invoice_getCompanyInvoiceInfo_error",
              msg:this.t("invoice_msg_three"),
              err
            },
            level: 'WARNING',
            type: 'UnifyGoods'
          })
        });
      },
      changeInvoiceMessage(val) {
        this.invoiceMessage = {
          invoiceHead: val.invoice_title || '',
          taxNumber: val.invoice_tax_number || '',
          invoiceType: val.invoice_type || 1,
          invoiceCategory: val.content_type || 1,
          invoiceEmail: val.invoice_email || '',
          invoiceState: val.is_open_invoice || 0,
          invoicePhone: val.invoice_phone || '',
          invoiceTaxAddress: val.invoice_tax_address || '',
          invoiceTaxPhone: val.invoice_tax_phone || '',
          invoiceTaxBank: val.invoice_tax_bank || '',
          invoiceTaxBankAccount: val.invoice_tax_bank_account || '',
        }
        this.choiceType(this.invoiceMessage.invoiceType)
        this.choiceClass(this.invoiceMessage.invoiceCategory)
      },
      //使用微信抬头
      onUseWechat() {
        let that = this;
        window.wx?.invoke("chooseInvoiceTitle", { scene: "1" }, function (res) {
          let invoiceData = JSON.parse(res.choose_invoice_title_info);
          that.choiceType(Number(invoiceData.type) + 1);
          that.invoiceMessage.invoiceHead = invoiceData.title;
          that.invoiceMessage.taxNumber = invoiceData.taxNumber;
        });
      },
      //选择发票类型
      choiceType(id) {
        if (id === 1) {
          this.invoiceForm[0].class = "active theme-customize-bg-light theme-customize-border";
          this.invoiceForm[1].class = "";
        } else if (id === 2) {
          this.invoiceForm[1].class = "active theme-customize-bg-light theme-customize-border";
          this.invoiceForm[0].class = "";
        }
        this.invoiceMessage.invoiceType = id;
        this.invoiceMessage.invoiceCategory =
          this.invoiceClass.length > 0 ? this.invoiceClass[0].id : 1;
        this.invoiceClass.length > 0 && (this.invoiceClass[0].class = "active theme-customize-bg-light theme-customize-border");
        this.invoiceClass.length > 1 && (this.invoiceClass[1].class = "");
        this.invoiceContent = this.t("invoice_goods_categories");
      },
      //选择发票类别
      choiceClass(id) {
        if (this.invoiceMessage.invoiceCategory !== id) {
          this.invoiceClass[id - 1].class = "active theme-customize-border theme-customize-bg-light";
          this.invoiceClass[this.invoiceMessage.invoiceCategory - 1].class = "";
        }
        id === 1
          ? (this.invoiceContent = this.t("invoice_goods_categories"))
          : (this.invoiceContent = this.t("invoice_detailed_product"));
        this.invoiceMessage.invoiceCategory = id;
      },
      //检查输入格式
      checkInput(val) {
        let flag = true;
        for (let item in val) {
          switch (item) {
            case "invoiceHead":
              if (val[item] || val[item].length > 0) {
                continue;
              } else {
                flag = this.t("invoice_fill_invoice_title");
                return flag;
              }
            case "taxNumber":
              if (val.invoiceType === 2) {
                continue;
              } else if (val[item] || val[item].length > 0) {
                continue;
              } else {
                flag = this.t("invoice_fill_enterprise_duty");
                return flag;
              }
            case "invoiceEmail":
              if (val[item] || val[item].length > 0) {
                if (
                  /^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@([A-Za-z0-9-]+\.)+[A-Za-z]{2,6}$/.test(
                    val[item]
                  )
                ) {
                  continue;
                } else {
                  flag =  this.t("invoice_correct_email");
                  return flag;
                }
              } else {
                flag =  this.t("invoice_fill_email");
                return flag;
              }
            case "invoicePhone":
              if (val[item] || val[item].length > 0) {
                if (/^[1]([3-9])[0-9]{9}$/.test(val[item])) {
                  continue;
                } else {
                  flag = this.t("invoice_msg_two");
                  return flag;
                }
              } else {
                flag = this.t("invoice_msg_one");
                return flag;
              }
            default:
              break;
          }
        }
        return flag;
      },
      //提交
      onSubmit() {
        let flag = this.checkInput(this.invoiceMessage);
        if (flag !== true) {
          this.$toast(flag);
        } else {
          let that = this;
          this.invoiceMessage.invoiceState = 1;
          this.$emit("getInvoiceMsg", that.invoiceMessage);
          this.$emit("closeSelect");
        }
      },
      //关闭发票选择器
      onCloseInvoiceSelect() {
        this.$emit("closeSelect");
      },
      //确定发票类别
      onEnsureInvoiceClass() {
        this.invoiceClassData = this.shopConf.invoice_type || [];
        const detail = this.invoiceClassData.includes("GOODS_DETAIL");
        const cate = this.invoiceClassData.includes("GOODS_CATEGORY");
        this.invoiceClass = [];
        if (cate) {
          this.invoiceClass.push({ id: 1, title: this.t("invoice_Goods_Categories"), class: "active theme-customize-border theme-customize-bg-light" });
        }
        if (detail) {
          this.invoiceClass.push({ id: 2, title: this.t("invoice_Goods_Detail"), class: "active theme-customize-border theme-customize-bg-light" });
        }
        switch (this.invoiceClass.length) {
          case 2:
            this.invoiceClass[1].class = "";
            this.invoiceContent =  this.t("invoice_goods_categories");
            break;
          case 1:
            this.invoiceMessage.invoiceCategory = this.invoiceClass[0].id;
            this.invoiceClass[0].id === 1
              ? (this.invoiceContent = this.t("invoice_goods_categories"))
              : (this.invoiceContent = this.t("invoice_detailed_product"));
            break;
          case 0:
            this.showClass = false;
        }
      },
      //失去焦点
      onBlur() {
        //防止ios软键盘收回后，页面不复位
        setTimeout(function () {
          document.body.scrollTop = document.body.scrollHeight;
        }, 0);
      },
      //得到焦点
      onFocus() {
        //ios软键盘弹出后，使完成按钮移到软键盘上方
        setTimeout(function () {
          document.body.scrollTop = document.body.scrollHeight;
        }, 200);
      },
      // 展示/收起更多选填项
      isShowInfo() {
        this.showInfo = !this.showInfo
      },
      // 注册电话校验
      clearNoNum(value) {
        value = value.replace(/[\u4e00-\u9fa5]/gm, '')
        value = value.replace(/[a-zA-Z]+/g, '')
        value = value.replace(/\s+/g, '')
        return value
      }
    },
  };
  </script>
  
  <style lang="scss" scoped>
  @import "../../assets/styles/global.scss";
  @import "../../assets/styles/common.scss";
  .invoice-select {
    height: 80%;
    overflow-y: hidden;
    max-width: 480px;
    right: auto;
  
    .invoice-select-inner {
      height: 100%;
      display: flex;
      flex-direction: column;
  
      .close-input {
        position: absolute;
        top: 0.32rem;
        right: 0.32rem;
        color: #bfbfbf;
      }
  
      .invoice-select-title {
        font-weight: 500;
        padding: 0.32rem 0;
        text-align: center;
      }
  
      .invoice-select-content {
        padding: 0 0.32rem 2.6rem 0.32rem;
        overflow-y: scroll;
        height: 100%;
  
        .use-wechat {
          font-weight: 500;
  
          span {
            color: #09bb07;
          }
        }
  
        .invoice-select-tip {
          display: flex;
          justify-content: space-between;
  
          .type-title {
            font-weight: 500;
          }
        }
  
        .invoice-select-remind {
          line-height: 1.5;
        }
  
        .invoice-select-button {
          button {
            background: #f5f5f5;
            border-radius: 0.28rem;
            padding: 0.1rem 0.32rem;
            margin-right: 0.24rem;
          }
  
          .active {
            border-width: 0.02rem;
            border-style: solid;
          }
        }
  
        .input-top {
          font-weight: 400;
        }
  
        .invoice-head {
          position: relative;
  
          .invoice-head-list {
            position: absolute;
            z-index: 999;
            left: 0;
            top: 0.96rem;
            width: 100%;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
            border-radius: 0.08rem;
            border: 1px solid #e4e7ed;
            box-sizing: border-box;
            background-color: #fff;
            padding: 0.2rem 0.4rem;
            overflow-y: auto;
            max-height: 4rem;
  
            .head-item {
              line-height: 0.68rem;
            }
          }
  
          .invoice-head-list::after {
            position: absolute;
            content: " ";
            left: 0.4rem;
            top: -0.12rem;
            width: 0;
            height: 0;
            border-bottom: 0.12rem solid #fff;
            border-right: 0.12rem solid transparent;
            border-left: 0.12rem solid transparent;
          }
        }
  
        .invoice-select-input {
          border-radius: 2px;
          border: 1px solid #dbdbdb;
          padding: 0.24rem;
  
          input {
            width: 100%;
            border: 0;
            padding: 0;
  
            &::-webkit-input-placeholder {
              /* placeholder颜色 */
              color: #b2b2b2;
            }
  
            &:-ms-input-placeholder {
              /* placeholder颜色 */
              color: #b2b2b2;
            }
  
            &:-moz-placeholder {
              /* placeholder颜色 */
              color: #b2b2b2;
            }
  
            &::-moz-placeholder {
              /* placeholder颜色 */
              color: #999999;
            }
          }
        }
  
        .invoice-select-moreInfo {
          display: flex;
          justify-content: space-between;
  
          .show-info {
            display: flex;
            padding-top: 0.05rem;
  
            img {
              width: 0.28rem;
              height: 0.28rem;
            }
          }
        }
  
        .invoice-select-info {
          input {
            &::-webkit-input-placeholder {
              /* placeholder颜色 */
              color: #b2b2b2;
            }
  
            &:-ms-input-placeholder {
              /* placeholder颜色 */
              color: #b2b2b2;
            }
  
            &:-moz-placeholder {
              /* placeholder颜色 */
              color: #b2b2b2;
            }
  
            &::-moz-placeholder {
              /* placeholder颜色 */
              color: #999999;
            }
          }
        }
  
        .input-border {
          border: none;
        }
  
        .invoice-select-category {
          padding: 0.4rem 0;
        }
      }
  
      .invoice-select-foot {
        background: #fff;
        padding: 0.16rem 0.28rem;
        box-sizing: border-box;
        border-top: 0.02rem solid #eee;
  
        button {
          width: 100%;
          color: #fff;
          border-radius: 0.4rem;
          padding: 0.2rem 0;
        }
      }
    }
  }</style>